package com.siha_back.interceptor;

import com.siha_back.utils.JwtUtil;
import com.siha_back.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        //验证token
        if (token == null || token.length() == 0) {
            response.setStatus(401);
            return false;
        }
        Map<String, Object> claims;
        String cacheKey = "UserToken:" + token;
        //先从缓存中获取结果
        Map<Object,Object> cacheResult=redisTemplate.opsForHash().entries(cacheKey);
        //缓存中存在，直接使用
        if(!cacheResult.isEmpty()){
            claims=new HashMap<>();
            for(Map.Entry<Object,Object> entry:cacheResult.entrySet()){
                claims.put(entry.getKey().toString(),entry.getValue());
            }
        }else{
            try {
                //缓存中不存在，进行解析
                claims=JwtUtil.parseToken(token);
                //将解析结果存入缓存，并设置过期时间和Token有效期一致
                redisTemplate.opsForHash().putAll(cacheKey, claims);
                //设置token有效期为30min,缓存有效期也为30min
                redisTemplate.expire(cacheKey,30, TimeUnit.MINUTES);
            }catch (Exception e){
                //token解析失败
                response.setStatus(401);
                return false;
            }
        }
        //把业务数据存储到ThreadLocal中
        ThreadLocalUtil.set(claims);
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
